package com.yuandengta.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author:Hardy
 * @QQ:2937270766
 * @官网：http://www.yuandengta.com
 */
public class GroupChatServer {
    private int port;

    public GroupChatServer(int port){
        this.port = port;
    }

    //编写run方法，处理客户端请求
    public void run() throws  Exception{
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
        .childOption(ChannelOption.SO_KEEPALIVE,true)
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder",new StringDecoder());//解码器
                pipeline.addLast("encoder",new StringEncoder());//编码器
                pipeline.addLast(new GroupChatServerHandler());
            }
        });
        System.out.println("netty服务器启动");
        ChannelFuture channelFuture = b.bind(port).sync();

        //监听关闭
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws Exception {
        new GroupChatServer(7000).run();
    }
}
